// import delay from 'mocker-api/utils/delay'; // 延时 模拟请求异步问题
const Mock = require('mockjs');
const NewsData = require('./news');
const ShopData = require('./shop');

// import mockjs from 'mockjs';
// import NewsData from'./news';

const Query = (options, dataSource) => {
  let { current, pageSize, ...other } = options;
  current = current || 1;
  pageSize = pageSize || 10;
  for (let key in other) {
    if ({}.hasOwnProperty.call(other, key)) {
      dataSource = dataSource.filter(item => {
        if ({}.hasOwnProperty.call(item, key)) {
          return String(item[key]).trim().indexOf(decodeURI(other[key]).trim()) > -1
        }
        return true
      })
    }
  }
  return { current, pageSize, dataSource }
}

const data = {
  'GET /api/user': {
    data: {
      id: 1,
      username: 'kenny',
      sex: 6
    },
    statusCode: '200'
  },
  'GET /api/hi': (req, res) => {
    res.json(
      {
        id: 1,
        //query 方法获取Get参数,如 /api/hi?name=tony
        username: req.query["name"],
      }
    )
  },
  'GET /api/news/list': (req, res) => {
    const { query } = req;
    const { current, pageSize, dataSource } = Query(query, NewsData.data.lists);
    res.status('200').json({
      data: {
        lists: dataSource.slice((current - 1) * pageSize, current * pageSize),
        pageInfo: {
          current: Number(current),
          pageSize: Number(pageSize),
          total: dataSource.length,
          maxCurrent: dataSource.length % pageSize >= 0 ? Math.ceil(dataSource.length / pageSize) : dataSource.data.length / pageSize
        }
      },
      statusCode: '200'
    })
  },
  'GET /api/shop/list': (req, res) => {
    const { query } = req;
    const { current, pageSize, dataSource } = Query(query, ShopData.data.lists);
    res.status('200').json({
      data: {
        lists: dataSource.slice((current - 1) * pageSize, current * pageSize),
        pageInfo: {
          current: Number(current),
          pageSize: Number(pageSize),
          total: dataSource.length,
          maxCurrent: dataSource.length % pageSize >= 0 ? Math.ceil(dataSource.length / pageSize) : dataSource.data.length / pageSize
        }
      },
      statusCode: '200'
    })
  }
}

Mock.mock('/getShopList','post', (req, res) => {
  const { query } = req;
  const { current, pageSize, dataSource } = Query(query, ShopData.data.lists);
  res.status('200').json({
    data: {
      lists: dataSource.slice((current - 1) * pageSize, current * pageSize),
      pageInfo: {
        current: Number(current),
        pageSize: Number(pageSize),
        total: dataSource.length,
        maxCurrent: dataSource.length % pageSize >= 0 ? Math.ceil(dataSource.length / pageSize) : dataSource.data.length / pageSize
      }
    },
    statusCode: '200'
  })
})
//使用delay方法可以延迟返回数据
// module.exports = data
